/**
 * Copyright (c) 2007-2008 Nearchos Paspallis
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * AspectSense
 *
 * Middleware for annotation-based, context-aware and adaptive services for
 * mobile and ubiquitous computing
 *
 * This project is an open-source effort, initiated by Nearchos Paspallis as
 * part of his PhD work at the University of Cyprus (http://www.ucy.ac.cy).
 *
 * More information about the project is available at "http://aspectsense.org".
 */

package org.aspectsense.gui.client.tree;

import org.aspectsense.framework.MonitoringManagement;
import org.aspectsense.framework.RequiredServiceMetadata;
import org.aspectsense.metadata.ComponentMetadata;
import org.aspectsense.util.Miscellaneous;
import org.aspectsense.gui.util.WindowPopups;

import javax.swing.tree.TreeNode;
import java.util.*;
import java.rmi.RemoteException;

/**
 * @author Nearchos Paspallis [nearchos@cs.ucy.ac.cy]
 *         Date: Jan 8, 2008
 *         Time: 12:04:56 PM
 */
public class ServicesTreeNode extends DefaultTreeNode
{
    public static final String [] EMPTY_STRING_ARRAY = new String[0];

    public static final String SERVICES_ROOT = "Installed services view";

    private HashMap<String, Set<ComponentMetadata>> serviceProvidedBy
            = new HashMap<String, Set<ComponentMetadata>>();

    private HashMap<String, Set<ComponentMetadata>>
            serviceRequiredBy = new HashMap<String, Set<ComponentMetadata>>();

    public ServicesTreeNode(final String [] installedComponentIDs, final MonitoringManagement monitoringManagement)
            throws RemoteException
    {
        super(null);

        assert installedComponentIDs != null && monitoringManagement != null;

        // compute the service providers and service requestors
        for(final String installedComponentID : installedComponentIDs)
        {
            final ComponentMetadata componentMetadata
                    = monitoringManagement.getComponentMetadata(installedComponentID);

            // compute the service providers
            {
                final String providedServiceID
                        = componentMetadata.getProvidedService().getServiceTypeCanonicalName();
                Set<ComponentMetadata> serviceProviders = serviceProvidedBy.get(providedServiceID);
                if(serviceProviders == null)
                {
                    serviceProviders = new HashSet<ComponentMetadata>();
                    serviceProvidedBy.put(providedServiceID, serviceProviders);
                }
                serviceProviders.add(componentMetadata);
            }

            // compute the service requestors
            {
                final Map<String, RequiredServiceMetadata> requiredServiceMetadataMap
                        = componentMetadata.getRequiredServices();
                final Collection<RequiredServiceMetadata> requiredServiceMetadataCollection
                        = requiredServiceMetadataMap.values();
                for(final RequiredServiceMetadata requiredServiceMetadata : requiredServiceMetadataCollection)
                {
                    final String requiredServiceID
                            = requiredServiceMetadata.getServiceTypeCanonicalName();

                    Set<ComponentMetadata> serviceRequestors
                            = serviceRequiredBy.get(requiredServiceID);
                    if(serviceRequestors == null)
                    {
                        serviceRequestors = new HashSet<ComponentMetadata>();
                        serviceRequiredBy.put(requiredServiceID, serviceRequestors);
                    }
                    serviceRequestors.add(componentMetadata);
                }
            }
        }

        final String [] installedServiceIDs
                = monitoringManagement.getInstalledServiceIDs();

        for(final String serviceID : installedServiceIDs)
        {
            children.add(new ServiceTreeNode(this, serviceID, monitoringManagement));
        }
    }

    public String toString()
    {
        return SERVICES_ROOT;
    }

    class ServiceTreeNode extends DefaultTreeNode
    {
        private final String serviceName;

        ServiceTreeNode(
                final TreeNode parent,
                final String serviceID,
                final MonitoringManagement monitoringManagement)
        {
            super(parent);

            this.serviceName = Miscellaneous.partAfterLastDot(serviceID);

            final Set<ComponentMetadata> providers
                    = serviceProvidedBy.get(serviceID);
            final Set<ComponentMetadata> requestors
                    = serviceRequiredBy.get(serviceID);

            if(providers != null && !providers.isEmpty())
            {
                children.add(new ServiceProvidersTreeNode(this, providers, serviceID, monitoringManagement));
            }
            if(requestors != null && !requestors.isEmpty())
            {
                children.add(new ServiceRequirersTreeNode(this, requestors));
            }
        }

        public String toString()
        {
            return serviceName;
        }
    }

    class ServiceProvidersTreeNode extends DefaultTreeNode
    {
        private double maxUtility = 0;

        ServiceProvidersTreeNode(
                final TreeNode parent,
                final Set<ComponentMetadata> serviceProviders,
                final String serviceID,
                final MonitoringManagement monitoringManagement)
        {
            super(parent);

            if(serviceProviders != null)
            {
                for(final ComponentMetadata componentMetadata : serviceProviders)
                {
                    final String componentID = componentMetadata.getComponentTypeCanonicalName();
                    final String name = componentMetadata.getDisplayID();
                    final String description = componentMetadata.getDescription();

                    double utility = -1;
                    try
                    {
                        utility = monitoringManagement.getServiceUtility(serviceID, componentID);
                    }
                    catch (RemoteException re)
                    {
                        WindowPopups.showError(null,
                                "Error while computing the utility of service: "
                                        + serviceID + " provided by component: "
                                        + componentID + " (embedded exception: "
                                        + re.getMessage() + ", caused by: "
                                        + re.getCause() + ")");
                    }

                    if(utility > maxUtility) maxUtility = utility;
                    final String utilityS
                            = Miscellaneous.formatDoubleWithTwoDigitsMax(utility);
                    final String tooltip = "<html>Name: <i>" + name + "</i>" +
                            "<br></br>Type: <i>" + componentID + "</i>" +
                            "<br></br>Description: <i>" + description + "</i>" +
                            "<br></br>Utility: <i>" + utilityS + "</i>" + "</html>";
                    children.add(new DefaultStringTreeNode(
                            this,
                            name + " (utility: " + utilityS + ")",
                            tooltip));
                }
            }
        }

        public String toString()
        {
            return "Provided by (Max-utility: "
                    + Miscellaneous.formatDoubleWithTwoDigitsMax(maxUtility)
                    + ")";
        }
    }

    class ServiceRequirersTreeNode extends DefaultTreeNode
    {
        ServiceRequirersTreeNode(final TreeNode parent, final Set<ComponentMetadata> serviceRequestors)
        {
            super(parent);

            if(serviceRequestors != null)
            {
                for(final ComponentMetadata componentMetadata : serviceRequestors)
                {
                    final String name = componentMetadata.getDisplayID();
                    final String type = componentMetadata.getComponentTypeCanonicalName();
                    final String tooltip = "<html>Name: <i>" + name + "</i>" +
                            "<br></br>Type: <i>" + type + "</i><br/>" +
                            "</html>";
                    children.add(new DefaultStringTreeNode(
                            this,
                            name,
                            tooltip));
                }
            }
        }

        public String toString()
        {
            return "Required by";
        }
    }
}